<template>
  <span class="view-count">{{ viewCount }}</span>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vitepress'
import { getGlobalVersion } from '../composables/useVersion'

const route = useRoute()
const viewCount = ref('加载中...')

// 获取页面访问量
const getPageViewCount = async () => {
  try {
    const currentVersion = getGlobalVersion()
    const response = await fetch(`/api/stats?version=${encodeURIComponent(currentVersion)}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      mode: 'cors',
      credentials: 'omit' // 不发送 cookies，避免跨域问题
    })
    if (response.ok) {
      const data = await response.json()
      const currentPath = route.path
      const pageData = data.data?.popularPages?.find((page: any) => page.path === currentPath)
      viewCount.value = pageData ? `${pageData.views}` : '0'
    } else {
      viewCount.value = '0'
    }
  } catch (error) {
    console.error('获取页面访问量失败:', error)
    viewCount.value = '0'
  }
}

// 监听路由变化
watch(() => route.path, () => {
  getPageViewCount()
})

onMounted(() => {
  getPageViewCount()
})
</script>

<style scoped>
.view-count {
  font-weight: 500;
}
</style> 